<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>005防抖函数</title>
</head>
<body>
    <div class="wrap">
        <input type="text" id="ipt">
    </div>
    <script>
        const oIpt = document.getElementById('ipt')
        function handleInput(e) {
            console.log('test debounce', this, e)
        }

        function debounce(source, delay) {
            let timer = null
            let myDebounce =  function(...args) {
                const context = this
                if(timer) {
                    clearTimeout(timer)
                }
                timer = setTimeout(() => {
                    // 2 当input事件触发时，myDebounce回调函数会被执行，此时只需通过apply将myDebounce函数的this和参数绑定给source，使其保持一致即可。
                    source.apply(context, args)
                    timer = null
                }, delay);
            }
            return myDebounce
        }
        // 1 handleInput函数经过 防抖函数 处理，得到一个myDebounce函数。
        let fn = debounce(handleInput, 300)
        oIpt.addEventListener('input', fn)
    </script>
</body>
</html>